#include "screen.h"
#include "system.h"

unsigned char* textmem;
int attribute = 0x07;
int cursor_x = 0;
int cursor_y = 0;

void clear_screen_text()
{
	int i, j;
	
	for( i = 0; i < 25; i++ )
		for( j = 0; j < 80; j++) {
			textmem[((i*80) + j)*2] = ' ';
			textmem[((i*80) + j)*2+ 1] = attribute;
		}
}

void move_cursor()
{
	unsigned pos = cursor_y * 80 + cursor_x;

	outportb(0x3D4, 14);
	outportb(0x3D5, pos>>8);
	outportb(0x3D4, 15);
	outportb(0x3D5, pos);
}

void scroll()
{
	unsigned short pos;
	int i;

	if (cursor_y >= 25) {
		pos = cursor_y - 25 + 1;
		kmemcpy ( textmem, textmem + pos * 80 * 2, (25 - pos) * 80 * 2);
		for( i = 0; i < 80; i++ ) {
			textmem  [((25 - pos) * 80 + i) * 2] = ' ';
			textmem  [(((25 - pos) * 80 + i) * 2) + 1] = attribute;
		}
		cursor_y = 25 - 1;
	}
}

void kputch(unsigned char c)
{
	unsigned char* pos;
	if ( c == 0x08 ) {
		if (cursor_x > 0 ) cursor_x--;
	}
	else if ( c == 0x09 ) {
		cursor_x = (cursor_x + 8) &  ~(8 - 1);
	} else if ( c == '\r' ) {
		cursor_x = 0;
	} else if ( c == '\n' ) {
		cursor_x = 0;
		cursor_y++;
	} else if ( c >= ' ') {
		pos = textmem + ((cursor_y * 80) + cursor_x) * 2;
		pos[0] = c;
		pos[1] = attribute;
		cursor_x ++;
	}
	
	if ( cursor_x >= 80 ) {
		cursor_x = 0;
		cursor_y++;
	}

	scroll();
	move_cursor();
}

void kputs(unsigned char* s)
{
	int i;
	for ( i = 0; i < strlen(s); i++) {
		kputch(s[i]);
	}
}

void kputhexb(unsigned char h)
{
	kputs("0x");
	if (h/16 > 9) {
		kputch(h/16-9 + 'A');
	} else {
		kputch(h/16 + '0');
	}
	if (h%16 > 9) {
		kputch((h%16)-9 + 'A');
	} else {
		kputch((h%16) + '0');
	}

}

void init_screen_text()
{
	textmem = (unsigned char*)0xB8000;
	clear_screen_text();
}

extern void set_attribute_text(unsigned char forecolor, unsigned char backcolor)
{
	attribute = (backcolor<<4)|(forecolor & 0x0F);
}
